package top.lcm889.oj.offer.按数据结构分类.链表;

import java.util.List;

/**
 * @author Coder-lcm
 * @date 2021/2/5
 */
public class T18_删除链表的节点 {
    public static ListNode deleteNode(ListNode head, int val) {
        if (head == null){
            return null;
        }
        ListNode res = new ListNode(-1);
        while (head != null){
            if (head.val != val){
                ListNode next = head.next;
                head.next = res.next;
                res.next = head;
                head = next;
                continue;
            }
            head = head.next;
        }
        return reverse(res.next);
    }

    public static ListNode reverse(ListNode head) {
        ListNode newList = new ListNode(-1);
        while (head != null) {
            ListNode next = head.next;
            head.next = newList.next;
            newList.next = head;
            head = next;
        }
        return newList.next;
    }


    public static void main(String[] args) {
        ListNode res = deleteNode(new ListNode(4, new ListNode(5, new ListNode(1,new ListNode(9)))), 5);
        while (res != null){
            System.out.println(res.val);
            res = res.next;
        }
    }
}
